<template>
  <div class="main">
    <div class="work A">
      <li><h2>个人信息</h2></li>
      <li>
        <div class="AvaName">
          <el-avatar shape="square" :size="100" :src="url"></el-avatar>
          <h3 class="name">{{ this.$store.state.writerData.writerName }}</h3>
        </div>
        <div class="changButton">
          <el-button type="text" @click="changeAvaVisible = true"
            >更换头像</el-button
          >
          <el-button type="primary" @click="changeMsgVisible = true"
            >修改用户名</el-button
          >
        </div>
      </li>
    </div>
    <div class="work B">
      <li><h2>加密信息</h2></li>
      <li>
        <el-button type="primary" @click="openClick">修改密码</el-button>
        <el-button type="primary" @click="changeTwoPassVisible = true"
          >忘记二级密码</el-button
        >
        <!-- 先向旧邮箱发送解绑验证码，输入新邮箱后发送绑定验证码 -->
        <el-button type="primary" @click="changeEmail">重新绑定邮箱</el-button>   
      </li>
    </div>
    <!-- <div class="work C">3</div> -->
    <!-- 修改用户名弹窗 -->
    <el-dialog
      title="输入新名字"
      :visible.sync="changeMsgVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
      <el-input type="text" v-model="name"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeChangeMsgVisible">取 消</el-button>
        <el-button type="primary" @click="changeMsg">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 更改头像弹窗 -->
    <el-dialog title="提示" :visible.sync="changeAvaVisible" width="50%">
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        action="http://127.0.0.1:3000/api/writersAva/"
        accept="image/jpg, image/jpeg, image/png"
        name="avatar"
        :on-success="onSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png/jpeg文件
        </div>
      </el-upload>
    </el-dialog>
    <!-- 初次设定二级密码弹窗 -->
    <el-dialog
      title="未设定二级密码，请先设定二级密码(六位)"
      :visible.sync="setTwoPassVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
      <span>输入密码</span>
      <el-input type="password" v-model="twoPassA" maxlength="6"></el-input>
      <span>确认密码</span>
      <el-input type="password" v-model="twoPassB" maxlength="6"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTwoPass">取 消</el-button>
        <el-button type="primary" @click="setTwoPass">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 更改二级密码弹窗 -->
    <el-dialog
      title="验证码将发到绑定邮箱，请输入"
      :visible.sync="changeTwoPassVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
      <span>输入新二级密码</span>
      <el-input type="password" v-model="twoPassA" maxlength="6" minlength="6"></el-input>
      <span>输入验证码</span>
      <el-input type="text" v-model="twoPassB" maxlength="5" minlength="5"></el-input>
      <el-button type="text" @click="getYan">获取验证码</el-button>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTwoPass">取 消</el-button>
        <el-button type="primary" @click="changeTwoPass">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 更改密码弹窗 -->
    <el-dialog
      title="输入新密码"
      :visible.sync="changePassWordVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
      <el-form
        :model="regForm"
        :rules="regRules"
        ref="regFormRef"
        label-width="100px"
      >
        <el-form-item label="密码" prop="password">
          <el-input v-model="regForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="closeChangePassWord">取消</el-button>
          <el-button type="primary" @click="ChangePassWord">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 解绑弹窗 -->
    <el-dialog
      title="已向绑定邮箱发送验证码,请输入验证码"
      :visible.sync="getYanVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
    <el-input v-model="yanNumB"></el-input>
    <span slot="footer" class="dialog-footer">
        <el-button @click="closeGetYan">取 消</el-button>
        <el-button type="primary" @click="subGetYan">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 重新绑定弹窗 -->
    <el-dialog
      title="已向目标邮箱发送验证码,请输入验证码"
      :visible.sync="upEmailVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="50%"
    >
    <span>输入邮箱</span>
    <el-input v-model="newEmail" id="newEmail" :disabled="false"></el-input>
    <el-button type="text" @click="getNewYan">获取验证码</el-button>
    <el-col><span>输入验证码</span><el-input v-model="yanNumB"></el-input> </el-col>
    <span slot="footer" class="dialog-footer">
        <el-button @click="closeUpEmail">取 消</el-button>
        <el-button type="primary" @click="subUpEmail">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkPass = (rule, value, callback) => {
      const regPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$/;
      if (regPass.test(value)) {
        return callback();
      }
      callback(
        new Error(
          "必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-16 之间"
        )
      );
    };
    return {
      newEmail:"",
      upEmailVisible:"",
      yanNumB:"",//输入的验证码
      yanNum:"", //获取的验证码
      twoPassA: "",
      twoPassB: "",
      name: "",
      url: this.$store.state.writerData.writerAvatar,
      changeAvaVisible: false,
      changeMsgVisible: false,
      setTwoPassVisible: false,
      changePassWordVisible: false,
      changeTwoPassVisible:false,
      getYanVisible:false,
      upEmailVisible:false,
      regForm: {
        password: "",
      },
      regRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPass, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async changeMsg() {
      //console.log(this.name);
      //this.$http.post(`books/writerName/${window.sessionStorage.getItem("writerId")}`,{ name: this.name })
      const {
        data: res,
      } = await this.$http.post(
        `writers/changeData/${window.sessionStorage.getItem("writerId")}`,
        { name: this.name }
      );
      if (res == "OK") {
        window.sessionStorage.setItem("writerName", this.name);
        this.$store.state.writerData.writerName = this.name;
        this.changeMsgVisible = false;
        this.name = "";
      }
    },
    closeChangeMsgVisible() {
      this.changeMsgVisible = false;
      this.name = "";
    },
    onSuccess(res) {
      let url = `http://127.0.0.1:3000/uploads/writers/${res.file.filename}`;
      this.changeAva(url);
    },
    async changeAva(url) {
      const {
        data: res,
      } = await this.$http.post(
        `writers/changeAva/${window.sessionStorage.getItem("writerId")}`,
        { avatar: url }
      );
      if (res == "OK") {
        this.changeAvaVisible = false;
        window.sessionStorage.setItem("writerAvatar", url);
        this.$store.commit("writerAvatar", url);
        //this.url = url;
        this.$refs.upload.clearFiles();
      }
    },
    async openClick() {
      const { data: res } = await this.$http.get(
        `writers/twoPass/${window.sessionStorage.getItem("writerId")}`
      );
      if (res.twoPass == null) {
        this.setTwoPassVisible = true;
      } else {
        this.$prompt("请输入二级密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            if (value === res.twoPass) {
              this.changePassWordVisible = true;
            } else {
              this.$message.error("密码错误");
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      }
    },
    async setTwoPass() {
      //console.log(this.twoPassB.length);
      if (this.twoPassA === this.twoPassB && this.twoPassA.length > 5) {
        const {
          data: res,
        } = await this.$http.post(
          `writers/setTwoPass/${window.sessionStorage.getItem("writerId")}`,
          { twoPass: this.twoPassB }
        );
        if (res.status === 200) {
          this.setTwoPassVisible = false;
          this.$message.success("设置成功");
          this.twoPassB = this.twoPassA = "";
        }
      } else {
        this.$message.error("两次密码不一致,或输入长度不符合要求");
      }
    },
    closeTwoPass() {
      this.changeTwoPassVisible = false
      this.setTwoPassVisible = false;

      this.twoPassA = this.twoPassB = "";
    },
    async ChangePassWord() {
      const {
        data: res,
      } = await this.$http.post(
        `writers/changPass/${window.sessionStorage.getItem("writerId")}`,
        { password: this.regForm.password }
      );
      if (res.status === 200) {
        this.changePassWordVisible = false;
        this.$router.push("/writerLogin");
      }
      //console.log(res);
    },
    closeChangePassWord() {
      this.changePassWordVisible = false;
      this.$refs.regFormRef.resetFields();
    },
    async getYan(){
      const{data:res} = await this.$http.get(`writers/getEmail/${window.sessionStorage.getItem("writerId")}`)
      if(res.status == 200){
        const{data:resa} = await this.$http.post("/sendEmail/Yan",{email:res.data.email})
        this.yanNum = resa.data;
        //console.log(resa);
      }
      //this.$http.post("/sendEmail/Yan",{email:this.twoPassA})
    },
    async changeTwoPass(){
      if(this.twoPassB == this.yanNum && this.twoPassA.length == 6){
        const {data:res} = await this.$http.post(`writers/changeTwoPass/${window.sessionStorage.getItem("writerId")}`,
        {pass:this.twoPassA})
        if(res == 'OK'){
          this.changeTwoPassVisible = false;
          this.twoPassA = this.twoPassB = '';
          this.$message.success("更改成功")
        }
      }
      else{
        this.$message.error("验证码错误或二级密码不为六位")
      }
      //
    },
    async changeEmail(){
      //如果未获得验证码，才发送请求 x
      //如果已获得验证码且没刷新页面，不发送请求 x
      // if(!this.yanNum){
      const{data:res} = await this.$http.get(`writers/getEmail/${window.sessionStorage.getItem("writerId")}`)
      if(res.status == 200){
        const{data:resa} = await this.$http.post("/sendEmail/Yan",{email:res.data.email})
        this.yanNum = resa.data;
        //console.log(resa);
      // }
      }
      this.getYanVisible = true;
    },
    closeGetYan(){
      this.getYanVisible = false;
      this.yanNumB = ""
    },
    subGetYan(){  
      if(this.yanNumB == this.yanNum){
        this.getYanVisible = false;
        this.upEmailVisible = true;
        this.yanNumB = this.yanNum = ""
      }
      else{
        this.$message.error("验证码错误");
      }
    },
    async getNewYan(){
      if(this.newEmail != ""){
      document.getElementById("newEmail").disabled = true;
      const{data:res} = await this.$http.post("/sendEmail/Yan",{email:this.newEmail});
      if(res.status == 200){
        this.yanNum = res.data;
        this.$message.success("发送成功")
      }
      else{
        this.$message.error("失败")
      }
      }
      else{
        this.$message.error("请先输入邮箱")
      }
    },
    closeUpEmail(){
      document.getElementById("newEmail").disabled = false;
      this.upEmailVisible = false;
      this.newEmail = "";
      this.yanNumB = this.yanNum = "";
    },
    async subUpEmail(){
      if (this.yanNumB == this.yanNum && this.yanNum != ""){
        const {data:res} =await this.$http.post(`/writers/changeEmail/${window.sessionStorage.getItem("writerId")}`,
        {email:this.newEmail})
        //console.log(res);
        if(res == 'OK'){
          document.getElementById("newEmail").disabled = true;
          this.upEmailVisible = false;
          this.newEmail = "";
          this.yanNumB = this.yanNum = "";
        }
        else{
          this.$message.error("失败");
        }
      }
      else{
        this.$message.error("验证码错误");
      }
    }
  },

  created() {},
};
</script>

<style lang="less" scoped>
li {
  width: 100%;
  list-style: none;
  display: flex;
  align-items: center;
}
.main {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
}
.work {
  flex: 1;
}
.A {
  display: flex;
  flex-direction: column;
}
.A li:first-child {
  border-bottom: 2px solid rgb(187, 185, 185);
  height: 30%;
}
.A li:nth-child(2) {
  height: 70%;
  justify-content: space-between;
}
.name {
  align-self: start;
  margin-left: 15px;
}
.AvaName {
  display: flex;
}
.changButton {
  display: flex;
  flex-direction: column;
}

.B li:nth-child(1) {
  border-bottom: 2px solid rgb(187, 185, 185);
  height: 30%;
}
.B li:nth-child(2) {
  height: 70%;
}
</style>
